package drds.plus.sql_process.type.impl;

import drds.plus.sql_process.type.*;

/**
 * {@link Double}类型
 */
public class DoubleType extends CommonType<Double> {

    private final Calculator calculator = new AbstractCalculator() {

        public Object doAdd(Object v1, Object v2) {
            Double i1 = convert(v1);
            Double i2 = convert(v2);
            return i1 + i2;
        }

        public Object doSub(Object v1, Object v2) {
            Double i1 = convert(v1);
            Double i2 = convert(v2);
            return i1 - i2;
        }

        public Object doMultiply(Object v1, Object v2) {
            Double i1 = convert(v1);
            Double i2 = convert(v2);
            return i1 * i2;
        }

        public Object doDivide(Object v1, Object v2) {
            Double i1 = convert(v1);
            Double i2 = convert(v2);

            if (i2.equals(0.0d)) {
                return null;
            }
            return i1 / i2;
        }

        public Object doMod(Object v1, Object v2) {
            Double i1 = convert(v1);
            Double i2 = convert(v2);

            if (i2.equals(0.0d)) {
                return null;
            }

            return i1 % i2;
        }

    };

    public int encode(Object value, byte[] bytes, int offset) {
        Encoder.encode(this.convert(value), bytes, offset);
        return getLength(null);
    }

    public int getLength(Object value) {
        if (value == null) {
            return 1;
        } else {
            return 9;
        }
    }

    public DecodeResult decode(byte[] bytes, int offset) {
        Double v = Decoder.decodeDoubleObject(bytes, offset);
        return new DecodeResult(v, getLength(v));
    }

    public Double incr(Object value) {
        return this.convert(value) + 0.000001d;
    }

    public Double decr(Object value) {
        return this.convert(value) - 0.000001d;
    }

    public Double getMaxValue() {
        return Double.MAX_VALUE;
    }

    public Double getMinValue() {
        return Double.MIN_VALUE;
    }

    public Calculator getCalculator() {
        return calculator;
    }

    public int getSqlType() {
        return java.sql.Types.DOUBLE;
    }

}
